<template>
  <div>
    <DetailPanel
      :dataSource="detailData"
      :columns="detailColumns"
      :buttons="buttons"
      :title="title"
      :imgSrc="imgSrc"
      class="station-detail"
    >
      <template slot="price">
        <div style="display: flex; align-items: center">
          <div>
            {{
              detailData.staPriceType === 'DURATION'
                ? '阶梯功率计费标准：'
                : detailData.staPriceType === 'INTERVAL'
                ? '电量计费标准：'
                : '固定价格计费标准：'
            }}
          </div>
          <div v-if="detailData.staPriceType !== 'FIXED'">
            <div
              v-for="(item, index) in priceArr"
              :key="index"
              class="value-text"
            >
              {{ item }}
            </div>
          </div>
          <div v-else>
            <div
              v-for="(item, index) in priceArr"
              :key="index"
              class="value-text"
            >
              <span style="display: inline-block; width: 60px">{{
                item.price
              }}</span>
              <span>{{ item.power }}</span>
              <span>{{ item.time }}</span>
            </div>
          </div>
        </div>
      </template>
      <template slot="count">
        <div>
          <div v-for="(item, index) in countArr" :key="index">
            <span>{{ item.label }}：</span
            ><span class="value-text">{{ item.value }}</span>
          </div>
        </div>
      </template>
      <template slot="timecard">
        <div style="display: flex; align-items: center">
          <div>时长卡计费标准：</div>
          <div>
            <div
              v-for="(item, index) in timeCardArr"
              :key="index"
              class="value-text"
            >
              {{ item }}
            </div>
          </div>
        </div>
      </template>
      <template slot="merchantTimecard">
        <div style="display: flex">
          <div>通用时长卡计费标准：</div>
          <div>
            <div
              v-for="(item, index) in merchantTimeCardArr"
              :key="index"
              class="value-text"
            >
              {{ item }}
            </div>
          </div>
        </div>
      </template>
    </DetailPanel>
    <AddUser
      :id="stationId"
      :type="addUserType"
      :visible.sync="addUserVisible"
    ></AddUser>
    <PresentTimeCard
      v-if="presentTimeCardVisible"
      :visible.sync="presentTimeCardVisible"
      @refreshTable="refreshTable"
      :items="presentItems"
      :card-attr="detailData"
      :api="api"
    ></PresentTimeCard>
  </div>
</template>
<script>
import DetailPanel from '@/components/DetailPanel'
import PresentTimeCard from '@/components/PresentTimeCard'
import AddUser from './AddUser'
import { typeMap } from '@/utils/format'
import { getStationTimeCardRules, sendTimeCard } from '@/api/device'
export default {
  name: 'StationDetailPanel',
  components: { DetailPanel, AddUser, PresentTimeCard },
  props: {
    detailData: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      addUserVisible: false,
      addUserType: '',
      imgSrc: '',
      stationId: '',
      countArr: [],
      priceArr: [],
      timeCardArr: [],
      merchantTimeCardArr: [],
      title: '充电站名称：',
      presentTimeCardVisible: false,
      presentType: [],
      api: {},
      cardAttr: {},
      detailColumns: [
        {
          slot: 'price',
        },
        {
          slot: 'count',
        },
        {
          slot: 'timecard',
        },
        {
          slot: 'merchantTimecard',
        },
        {
          label: '电站时长卡是否按照阶梯扣费',
          formatter: (data) => (data.timecardPowerCharging ? '是' : '否'),
        },
        {
          label: '服务费',
          formatter: (data) => {
            var str = ``
            str = `${data.stationService}元/次`
            return str
          },
        },
        // {
        //   label: '服务费',
        //   formatter: (data) => {
        //     var str = ``
        //     if (
        //       data.electricServicePrice == null ||
        //       data.electricServicePrice == 0
        //     ) {
        //       if (data.stationService == null || data.stationService == 0) {
        //         str = `${data.durationServicePrice}元/小时`
        //       } else {
        //         str = `${data.stationService}元/次`
        //       }
        //     } else {
        //       str = `${data.electricServicePrice}元/度`
        //     }
        //     return str
        //   },
        // },
        {
          label: '充电站地址',
          value: 'stationAddress',
        },
        {
          label: '电费成本',
          formatter: (data) => {
            return data.electcost + '元/度'
          },
        },
        {
          label: '扣费模式',
          formatter: (data) => typeMap.payType[data.payType],
        },
        {
          label: '停用状态',
          value: 'unableCyclesDesc',
          // formatter: (data) => typeMap.stationStatus[data.status],
        },
        {
          label: '电站类型',
          formatter: (data) => typeMap.stationType[data.stationType],
        },
        {
          label: '电站管理员电话',
          value: 'customerServicePhone',
        },
        {
          label: '计费模式',
          formatter: (data) => typeMap.staPriceType[data.staPriceType],
        },
      ],
      buttons: [
        {
          label: '编辑电站',
          icon: 'el-icon-edit',
          type: 'primary',
          resourceId:
            '/web/device-management/station-management/detail/编辑电站',
          // ifRender: (data) => {
          //   return data.stationUserId === this.userId
          // },
          click: () => {
            this.$router.push({
              path: `/device/edit/${this.detailData.id}`,
            })
          },
        },
        // {
        //   label: '添加内部名单',
        //   icon: 'el-icon-plus',
        //   type: 'primary',
        //   resourceId:
        //     '/web/device-management/station-management/detail/添加内部名单',
        //   // ifRender: (data) => {
        //   //   return data.stationUserId === this.userId
        //   // },
        //   click: () => {
        //     this.addUserVisible = true
        //     this.addUserType = 'internal'
        //   },
        // },
        // {
        //   label: '添加免费名单',
        //   icon: 'el-icon-plus',
        //   type: 'primary',
        //   resourceId:
        //     '/web/device-management/station-management/detail/添加免费名单',
        //   // ifRender: (data) => {
        //   //   return data.stationUserId === this.userId
        //   // },
        //   click: () => {
        //     this.addUserVisible = true
        //     this.addUserType = 'white'
        //   },
        // },
        // {
        //   label: '赠送时长卡',
        //   icon: 'el-icon-present',
        //   type: 'primary',
        //   resourceId:
        //     '/web/device-management/station-management/detail/赠送时长卡',
        //   // ifRender: (data) => {
        //   //   return data.stationUserId === this.userId
        //   // },
        //   click: () => {
        //     this.presentTimeCardVisible = true
        //     this.presentItems = [
        //       'mobile',
        //       'confirmMobile',
        //       'timeCardType',
        //       'timeCardRule',
        //       'initialTime',
        //       'timeCardExpire',
        //     ]
        //     this.cardAttr = this.detailData
        //     this.api = {
        //       timeCardRule: getStationTimeCardRules,
        //       submit: sendTimeCard,
        //     }
        //   },
        // },
      ],
    }
  },
  // computed: {
  //   userId() {
  //     return this.$store.getters.userId
  //   },
  // },
  watch: {
    detailData: {
      handler(val, oldVal) {
        if (val && val !== oldVal) {
          this.title = this.title + val.stationName
          this.imgSrc =
            process.env.VUE_APP_BASE_URL_API +
            '/file-management/file/download?fileId=' +
            val.stationImg
          this.countArr = [
            {
              label: '端口数',
              value: val.deviceDataStatisticsVo.socketCount,
            },
            {
              label: '空闲',
              value: val.deviceDataStatisticsVo.socketIdleCount,
            },
            {
              label: '充电中',
              value: val.deviceDataStatisticsVo.socketChargeCount,
            },
            {
              label: '失联',
              value: val.deviceDataStatisticsVo.socketOfflineCount,
            },
            {
              label: '故障',
              value: val.deviceDataStatisticsVo.socketBreakCount,
            },
          ]
          this.stationId = this.detailData.id
          this.formatterPrice()
          this.formatterTimecard()
          this.formatterMerchantTimecard()
        }
      },
      deep: true,
    },
  },
  methods: {
    refreshTable() {},
    formatterPrice() {
      if (this.detailData.staPriceType === 'DURATION') {
        let ladderPriceArr = this.detailData.ladderPrice
          ? this.detailData.ladderPrice.split(',')
          : []
        let ladderPowerArr = this.detailData.ladderPower
          ? this.detailData.ladderPower.split(',')
          : []
        if (ladderPowerArr.length == 1) {
          this.priceArr.push(ladderPriceArr[0] + '元/小时')
        } else {
          ladderPriceArr.forEach((price, index) => {
            let obj =
              index == 0
                ? '≤' + ladderPowerArr[1] + 'w:' + price + '元/小时'
                : index === ladderPriceArr.length - 1
                ? '>' + ladderPowerArr[index] + 'w:' + price + '元/小时'
                : ladderPowerArr[index] +
                  '-' +
                  ladderPowerArr[index + 1] +
                  'w:' +
                  price +
                  '元/小时'
            this.priceArr.push(obj)
          })
        }
      } else if (this.detailData.staPriceType === 'INTERVAL') {
        let priceDscrptJson = JSON.parse(this.detailData.priceDscrptJson)
        priceDscrptJson.forEach((item, index) => {
          this.priceArr.push(
            `${index === 0 ? '00:00' : priceDscrptJson[index - 1].t}-${
              item.t
            } ：${item.pr}元/度`
          )
        })
      } else if (this.detailData.staPriceType === 'FIXED') {
        let priceDscrptJson = JSON.parse(this.detailData.priceDscrptJson)
        priceDscrptJson.forEach((item) => {
          item.spd.forEach((itemChild, indexChild) => {
            let obj = {}
            // if (item.spd.length === 1) {
            //   obj.price = `${item.lpr}元：`
            //   obj.time = `${itemChild.t}小时`
            // } else {
            //   obj.price = `${indexChild === 0 ? item.lpr + '元：' : ''}`
            //   obj.power = `${
            //     indexChild === 0 ? '≤' + item.spd[1].p : '>' + item.spd[1].p
            //   }w：`
            //   obj.time = `${itemChild.t}小时`
            // }
            if (item.spd.length === 1) {
              obj.price = `${item.lpr}元：`
              obj.time = `${itemChild.t}小时`
            } else if (item.spd.length === 2) {
              obj.price = `${indexChild === 0 ? item.lpr + '元：' : ''}`
              obj.power = `${
                indexChild === 0 ? '≤' + item.spd[1].p : '>' + item.spd[1].p
              }w：`
              obj.time = `${itemChild.t}小时`
            } else {
              obj.price = `${indexChild === 0 ? item.lpr + '元：' : ''}`
              if (indexChild === 0) {
                obj.power = `${'≤' + item.spd[1].p}w：`
              } else if (indexChild > 0 && indexChild < item.spd.length - 1) {
                obj.power = `${item.spd[indexChild].p}-${
                  item.spd[indexChild + 1].p
                }w:`
              } else {
                obj.power = `${'>' + item.spd[indexChild].p}w：`
              }
              obj.time = `${itemChild.t}小时`
            }
            this.priceArr.push(obj)
          })
        })

        console.log(this.priceArr)
      }
    },
    formatterTimecard() {
      if (!this.detailData.timeCardRule) {
        this.timeCardArr.push('不支持')
      } else {
        let timeCardRuleArr = this.detailData.timeCardRule.split(';')
        timeCardRuleArr.forEach((rule) => {
          let ruleArr = rule.split(',')
          ruleArr.length === 2 ? ruleArr.push('') : null
          let time = ruleArr[0] + '小时'
          let period = '(' + (ruleArr[2] ? ruleArr[2] + '天' : '无限') + '):'
          let price = ruleArr[1] + '元'
          let obj = time + period + price
          this.timeCardArr.push(obj)
        })
      }
    },
    formatterMerchantTimecard() {
      if (
        !this.detailData.merchantTimecardRules ||
        !this.detailData.merchantTimecardRules.length
      ) {
        this.merchantTimeCardArr.push('不支持')
      } else {
        this.detailData.merchantTimecardRules.forEach((rule) => {
          let time = rule.initialTime + '小时'
          let period =
            '(' +
            (rule.periodOfValidity ? rule.periodOfValidity + '天' : '无限') +
            '):'
          let price = rule.price / 100 + '元'
          let obj = time + period + price
          this.merchantTimeCardArr.push(obj)
        })
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.station-detail {
  &::v-deep img {
    width: 160px;
    height: 160px;
  }
}
.detail-wrapper {
  margin-bottom: 16px;
}
.value-text {
  color: #988ca4;
}
</style>
